package userhandler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
	"sync"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/userprofitlog"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
)

var wg sync.WaitGroup

// HandleSetUserStewardStatus 设置2.0服务是否开启
func HandleSetUserStewardStatus(ctx *gin.Context) {
	param := &request.SetUserStewardStatusReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	param.IsAdmin, _ = helper.GetIsAdminFromCtx(ctx)
	param.ParentId, _ = helper.GetParentIdFromCtx(ctx)

	isStaff := param.IsAdmin == helper.TypeNumIsAdminStaff
	if (isStaff && param.ParentId != 2) || (param.IsSteward != 1 && param.IsSteward != 2) {
		Response(ctx)("", CodeInvalidParam, nil)(OK)
		return
	}
	if param.IsAdmin != helper.TypeNumIsAdminAdministrator && param.IsAdmin != helper.TypeNumIsAdminOperator && !isStaff {
		Response(ctx)("", CodeInvalidParam, nil)(OK)
		return
	}

	if dao.NewUserDao().SetUserStewardStatus(param).Err != nil {
		Response(ctx)("", CodeInternalServerError, nil)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, true)(OK)
}

// 获取代理商用户列表
func HandleGetAgentUserList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.UserLoginIsAdmin = IsAdmin
	param.ParentId = userId // 当前登录用户ID
	param.IsAdmin = IsAdmin // 代理商
	param.IsPlace = 0

	data := dao.NewUserDao().GetAgentUserList(param)
	lists := data.Unwrap().([]*users.UserInfoWithAgent)
	for _, lst := range lists {
		userInfo := dao.NewUserDao().GetUserInfoById(lst.ParentId).Unwrap().(*users.UserModel)
		lst.ParentName = userInfo.UserName + "-" + userInfo.Name
		logic.NewUserLogic().FindAgentChildrenList(lst.ID, lst, IsAdmin)
	}

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 新增代理商用户
func HandleInsertAgentUser(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	userName, err := helper.GetUserNameFromCtx(ctx) // 获取当前登录用户名
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	id := dao.NewUserDao().InsertAgentUser(param).Unwrap().(int)
	if id <= 0 {
		Response(ctx)("新增失败", CodeError, true)(OK)
		return
	}

	// 新增代理商日志
	upl := userprofitlog.UserProfitLog{}
	upl.ParentId = param.ParentId
	upl.UserName = param.UserName
	upl.OperationUserId = userId
	upl.OperationUserName = userName
	upl.OperateIP = ctx.ClientIP()
	upl.Change = 0
	upl.IsPlace = 0
	upl.ProfitProportion = int8(param.ProfitProportion)
	upl.Description = "新增代理商用户"
	upl.UserId = id
	u := &users.UserModel{}
	dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, param, u)

	Response(ctx)("新增成功", CodeSuccess, true)(OK)
}

// 修改代理商用户
func HandleUpdateAgentUser(ctx *gin.Context) {
	isAdmin, err := helper.GetIsAdminFromCtx(ctx) // 获取当前登录用户ID
	userId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	userName, err := helper.GetUserNameFromCtx(ctx) // 获取当前登录用户名
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	//添加修改用户分成日志

	//查询该用户修改前的分成比例
	userInfo := dao.NewUserDao().GetUserInfoById(param.Id).Unwrap().(*users.UserModel)

	upl := userprofitlog.UserProfitLog{}
	upl.ParentId = param.ParentId
	upl.UserId = param.Id
	upl.UserName = param.UserName
	upl.OperationUserId = userId
	upl.OperationUserName = userName
	upl.OperateIP = ctx.ClientIP()
	upl.Change = int8(userInfo.ProfitProportion)
	upl.IsPlace = 0
	upl.ProfitProportion = int8(param.ProfitProportion)
	upl.Description = "修改代理商用户"

	dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, param, userInfo)

	// 代理商改成商户，合伙人改成代理商的权限设定，超级管理员才有权限
	if isAdmin != 1 && (userInfo.IsAdmin != 3 && param.IsAdmin == 3) {
		Response(ctx)("没有权限，需要联系管理员", CodeUpdateSuccess, nil)(OK)
		return
	}
	Response(ctx)("", CodeUpdateSuccess,
		dao.NewUserDao().UpdateAgentUser(param).Unwrap())(OK)
}

// 获取上级代理信息
func HandleGetSuperiorAgentInfo(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	isAdmin, err := helper.GetIsAdminFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	parentId, err := helper.GetParentIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	var userInfo *users.UserModel
	if isAdmin == 2 || isAdmin > helper.TypeNumIsAdminStaff { // 代理商、运营商
		userInfo = dao.NewUserDao().GetUserInfoById(userId).Unwrap().(*users.UserModel)
	} else if isAdmin == 4 { // 员工
		userInfo = dao.NewUserDao().GetUserInfoByParentId(parentId).Unwrap().(*users.UserModel)
	} else {
		userInfo = dao.NewUserDao().GetUserInfoById(2).Unwrap().(*users.UserModel)
	}

	Response(ctx)("", CodeSuccess, userInfo)(OK)
}

func HandleGetParentProfitProportion(c *gin.Context) {
	param := &struct {
		UserId int `json:"userId" form:"userId" `
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	userInfo := dao.NewUserDao().GetParentProfitProportion(param.UserId).Unwrap().(*users.UserModel)
	Response(c)("", CodeSuccess, userInfo)(OK)
}

func HandleGetUserById(c *gin.Context) {
	param := &struct {
		Id int `json:"userId" form:"id" `
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	userInfo := dao.NewUserDao().GetUserInfoById(param.Id).Unwrap().(*users.UserModel)
	Response(c)("", CodeSuccess, userInfo)(OK)
}

func HandleGetUserBranchById(c *gin.Context) {
	param := &struct {
		PlaceName string `json:"branchName" form:"branchName" `
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	userInfo := dao.NewUserDao().GetUserBranchById(param.PlaceName).Unwrap().([]users.AgentInfo)
	Response(c)("", CodeSuccess, userInfo)(OK)
}

func HandleGetUserAgentById(c *gin.Context) {
	isAdmin, err := helper.GetIsAdminFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &struct {
		AgentName string `json:"agentName" form:"agentName" `
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	userInfo := dao.NewUserDao().GetUserAgentById(param.AgentName, isAdmin).Unwrap().([]users.AgentInfo)
	Response(c)("", CodeSuccess, userInfo)(OK)
}

//删除分公司用户
func HandleDeleteUserBranch(c *gin.Context) {
	param := &struct {
		Id int `json:"userId" `
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//查询分公司用户是否含有网点
	placesList := dao.NewUserDao().GetUserBranchList(param.Id).Unwrap().([]placemodel.PlaceModel)
	//var ids []int
	//for _, placesVal := range placesList {
	//	ids = append(ids, placesVal.Id)
	//}
	//placesIds := []interface{}{ids}
	//err := dao.NewUserDao().PlacesBatchDelete("id in (?)", &placesIds)
	//if err != nil {
	//	Response(c)("删除失败", CodeError, err.Error())(OK)
	//	return
	//}
	if len(placesList) > 0 {
		Response(c)("存在下级网点，不允许删除", CodeError, false)(OK)
		return
	}

	//删除公司用户
	Response(c)("删除成功", CodeSuccess, dao.NewUserDao().DeleteUserById(param.Id).Unwrap())(OK)
}

//删除代理商用户
func HandleDeleteAgentUser(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)   // 获取当前登录用户ID
	userName, _ := helper.GetUserNameFromCtx(ctx) // 获取当前登录用户名
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &struct {
		Id int `json:"userId" `
	}{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()

	//userList := dao.NewUserDao().GetAgentInfo(param.Id).Unwrap().([]users.UserModel)
	//if len(userList) > 0 {
	//	Response(ctx)("存在下级用户，不允许删除", CodeError, false)(OK)
	//	return
	//}
	// 判断 用户名下是否有子用户
	c := dao.NewUserDao().CountUserByParentId(param.Id).Unwrap().(int64)
	if c > 0 {
		Response(ctx)("删除失败,存在下级用户", CodeError, false)(OK)
		return
	}

	// 判断 用户名下是否有直属门店
	cp := dao.NewUserDao().CountPlaceByUserId(param.Id).Unwrap().(int64)
	if cp > 0 {
		Response(ctx)("删除失败,存在下级门店", CodeError, false)(OK)
		return
	}

	userInfo := dao.NewUserDao().GetUserInfoById(param.Id).Unwrap().(*users.UserModel)
	//删除代理商
	isDelete := dao.NewUserDao().DeleteUserById(param.Id).Unwrap().(bool)
	if isDelete {
		upl := userprofitlog.UserProfitLog{}
		upl.ParentId = userInfo.ParentID
		upl.UserId = userInfo.ID
		upl.UserName = userInfo.UserName
		upl.OperationUserId = userId
		upl.OperationUserName = userName
		upl.OperateIP = ctx.ClientIP()
		upl.Change = int8(userInfo.ProfitProportion)
		upl.IsPlace = int8(userInfo.IsPlace)
		upl.ProfitProportion = int8(userInfo.ProfitProportion)
		upl.Description = "删除代理商用户"
		p := &request.AdminUserInsertReq{}
		dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, p, userInfo) // 添加订单操作日志
		Response(ctx)("删除成功", CodeSuccess, true)(OK)
		return
	} else {
		Response(ctx)("删除失败", CodeError, false)(OK)
		return
	}

	//if isDelete {
	//	Response(ctx)("删除成功", CodeSuccess, dao.NewUserDao().DeleteStatistical(param.Id))(OK)
	//}
}

//删除网点用户
func HandleDeletePlacesUser(c *gin.Context) {
	param := &struct {
		Id int `json:"userId" `
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	userList := dao.NewUserDao().GetPlacesUserInfo(param.Id).Unwrap().([]users.UserModel)
	placesList := dao.NewUserDao().GetUserBranchList(param.Id).Unwrap().([]placemodel.PlaceModel)
	if len(userList) > 0 || len(placesList) > 0 {
		Response(c)("存在下级用户，不允许删除", CodeError, false)(OK)
		return
	}
	//删除网点用户
	Response(c)("删除成功", CodeSuccess, dao.NewUserDao().DeleteUserById(param.Id).Unwrap())(OK)
}

//删除员工
func HandleDeleteUserById(c *gin.Context) {
	param := &struct {
		Id int `json:"userId" `
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()

	Response(c)("删除成功", CodeSuccess, dao.NewUserDao().DeleteUserById(param.Id).Unwrap())(OK)
}

//解绑微信
func HandleUnBindWxInfo(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	userName, _ := helper.GetUserNameFromCtx(ctx) // 获取当前登录用户名
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &struct { Id int `json:"userId"` }{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()

	userInfo := dao.NewUserDao().GetUserInfoById(param.Id).Unwrap().(*users.UserModel)
	// 解绑微信
	isBind := dao.NewUserDao().UpdateUserIsBind(param.Id).Unwrap().(bool)
	if isBind {
		upl := userprofitlog.UserProfitLog{}
		upl.ParentId = userInfo.ParentID
		upl.UserId = userInfo.ID
		upl.UserName = userInfo.UserName
		upl.OperationUserId = userId
		upl.OperationUserName = userName
		upl.OperateIP = ctx.ClientIP()
		upl.Change = int8(userInfo.ProfitProportion)
		upl.IsPlace = int8(userInfo.IsPlace)
		upl.ProfitProportion = int8(userInfo.ProfitProportion)
		upl.Description = "解绑微信"
		p := &request.AdminUserInsertReq{}
		dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, p, userInfo) // 添加订单操作日志
		Response(ctx)("解绑成功", CodeSuccess, true)(OK)
		return
	} else {
		Response(ctx)("解绑失败", CodeError, false)(OK)
		return
	}

}

// 修改用户类型 商户--> 代理商  代理商-->商户
func HandleChangeUserType(c *gin.Context) {
	param := &struct {
		Id      int `json:"userId" `
		IsPlace int `json:"isPlace" `
		IsAdmin int `json:"isAdmin"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("", CodeUpdateSuccess, dao.NewUserDao().UpdateUserType(param.Id, param.IsPlace, param.IsAdmin).Unwrap())(OK)

}

//查询所有用户
func HandleGetUser(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &struct {
		UserName string `json:"userName" form:"userName" `
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("", CodeUpdateSuccess, dao.NewUserDao().GetAllUser(param.UserName, userId).Unwrap().([]*users.AgentInfo))(OK)
}

//查询代理商和商户
func HandleGetAdminOrPlace(ctx *gin.Context) {
	param := &struct {
		UserName string `json:"userName" form:"userName" `
	}{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()

	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, err := helper.GetIsAdminFromCtx(ctx)
	parentId, err := helper.GetParentIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	if IsAdmin == helper.TypeNumIsAdminAdministrator || (IsAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		userId = 2
		IsAdmin = 2
	}

	Response(ctx)("", CodeUpdateSuccess, dao.NewUserDao().
		GetAdminUserOrPlaceUser(param.UserName, userId, IsAdmin).Unwrap().([]*users.AgentInfo))(OK)
}

//导入用户
func HandleUserImport(c *gin.Context) {
	var userImportModel []request.UserImportReq
	dingo.ErrorIf(c.Bind(userImportModel)).Unwrap()
	if len(userImportModel) > 40000 {
		Response(c)("一次最多只能导入40000条", CodeError, nil)(OK)
		return
	}
	count := len(userImportModel)
	var insertModel []request.UserImportReq
	var insertCount, startNum, endNum int
	for i := 0; i < 10; i++ {
		if count >= 4000 {
			count = count - 4000
			endNum += 4000
			insertModel = userImportModel[startNum:endNum]
			startNum += 4000
			insertCount += 4000
		} else {
			endNum += count
			insertModel = userImportModel[startNum:endNum]
			startNum += count
			insertCount = count
			count = 0
		}

		if count > 0 {
			wg.Add(1)
			go func() {
				defer wg.Done() //减去一个计数
				//导入用户
				dao.NewUserDao().InsertUserImport(insertModel)
				//UserImport(&insertModel)
			}()

			wg.Wait()
		} else {
			break
		}

	}

}

//func UserImport(param []request.UserImportReq) {

//}

//测试定时任务
func AgentIncomeStatistics(c *gin.Context) {

	//userIdArr := dao.NewUserDao().QueryChildUserIds(471).Unwrap().([]int)
	//placeIdArr := dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
	//
	//var userIds string
	//for _, u := range userIdArr {
	//	userIds += strconv.Itoa(u) + ","
	//}
	//
	//var placeIds string
	//for _, p := range placeIdArr {
	//	placeIds += strconv.Itoa(p) + ","
	//}

	//logic.NewTaskLogic().AgentIncomeStatistics(2, "pcl")
	//logic.NewTaskLogic().BranchIncomeStatistics(2, "pcl")
	//logic.NewTaskLogic().PlaceIncomeStatistics(2, "pcl")

	//param := request.CloseOrderReq{}
	//dingo.ErrorIf(c.Bind(&param)).Unwrap()
	//logic.NewOrderLogic().HandleCancelEndOrder(&param)
	//logic.NewTaskLogic().BranchIncomeStatistics(8, "pcl")
	//param := &struct {
	//	StatiTime string `json:"statiTime" form:"statiTime" `
	//}{}
	//dingo.ErrorIf(c.Bind(param)).Unwrap()
	//logic.NewTaskLogic().UpdateOrderStatistics(param.StatiTime)
	//logic.NewTaskLogic().BranchIncomeStatistics(5, "pcl")
	//logic.NewTaskLogic().AgentIncomeStatistics(2, "pcl")
	//userIdArr := dao.NewUserDao().QueryChildUserIds(139).Unwrap().([]int)
	//
	//placeModelLst := dao.NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
	//placeIdArr := make([]int, 0)
	//for _, placeModel := range placeModelLst {
	//	placeIdArr = append(placeIdArr, placeModel.Id)
	//}
	//
	//CompleteCount := dao.NewAgentCountDao().GetAgentTotalOrderCount(139, 1, 5, "pcl").Unwrap().(int64) // 已完成订单数
	//fmt.Println(CompleteCount, "下级代理", userIdArr, "下级网点", placeIdArr)
}

func SeparationAddress(c *gin.Context) {

	//查询全部
	models := dao.NewPlaceDao().GetPlaceArr().Unwrap().([]placemodel.PlaceModel)
	for _, v := range models {
		var updateModel placemodel.PlaceModel
		updateModel.Id = v.Id
		//切割地区字符串
		str := strings.Split(v.RegionIds, ",")
		//绑定省份
		if str[0] != "" {
			provinceId, _ := strconv.Atoi(str[0])
			updateModel.ProvinceId = provinceId
		} else {
			updateModel.ProvinceId = 0
		}
		//绑定市
		if str[1] != "" {
			cityId, _ := strconv.Atoi(str[1])
			updateModel.CityId = cityId
		} else {
			updateModel.CityId = 0
		}
		//绑定县
		if str[2] != "" {
			countyId, _ := strconv.Atoi(str[2])
			updateModel.CountyId = countyId
		} else {
			updateModel.CountyId = 0
		}
		//执行修改操作
		dao.NewPlaceDao().UpdatePlaceId(&updateModel).Unwrap()
	}
}

func GetUserDeviceInfo(c *gin.Context) {
	param := &struct {
		UserId int `json:"userId" form:"userId" `
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//查询所有下级用户
	userIdArr := dao.NewUserDao().QueryChildUserIds(param.UserId).Unwrap().([]int)
	if len(userIdArr) < 0 {
		Response(c)("这个可以处理掉了", CodeUpdateSuccess, false)(OK)
		return
	}

	placeModelLst := dao.NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
	placeIdArr := make([]int, 0)
	for _, placeModel := range placeModelLst {
		placeIdArr = append(placeIdArr, placeModel.Id)
	}

	if len(placeIdArr) < 0 {
		Response(c)("这个可以处理掉了", CodeUpdateSuccess, false)(OK)
		return
	}

	//查询设备
	var deviceModel []devices.DeviceModel
	db := global.Orm.Table("devices").Where("place_id in (?)", placeIdArr).Find(&deviceModel)
	if db.Error != nil && len(deviceModel) < 0 {
		Response(c)("这个可以处理掉了", CodeUpdateSuccess, false)(OK)
		return
	}

	//查询所有的网点
	Response(c)("这个可以处理掉了", CodeUpdateSuccess, deviceModel)(OK)
	return
}

//校验价格
func CheckPrices(c *gin.Context) {

	//查询网点
	var lst []int
	dbGetPlaces := global.Orm.Debug().Table("places").Select("id").Where("id >=20000 and id <=40000").Find(&lst)
	if dbGetPlaces.Error != nil {
		Response(c)("查询网点出问题了", CodeError, dbGetPlaces.Error.Error())(OK)
		return
	}

	global.Orm.Debug().Table("prices").Select("place_id").Where("place_id not in (?)", lst)

}

//查询代理商角色列表
func GetUserIsAdmin(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	IsAdmin, err := helper.GetIsAdminFromCtx(c)
	parentId, err := helper.GetParentIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(c.ShouldBindQuery(param)).Unwrap()
	param.UserLoginIsAdmin = IsAdmin
	// 当前登录用户ID
	if IsAdmin == helper.TypeNumIsAdminAdministrator || (IsAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		param.ParentId = 2
	} else {
		param.ParentId = userId
	}
	data := dao.NewUserDao().GetUserListByIsAdmin(param)
	lists := data.Unwrap().([]*users.UserInfoWithAgent)
	logic.NewUserLogic().FindAllIsAdminUserChildrenListBatch(lists, param.IsAdmin, 0)

	var TotalPage int64
	if param.PageSize > 0 {
		TotalPage = (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize)
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  TotalPage,
		Data:       data.Unwrap(),
	})(OK)
}

func GetUserStaticticsByIsAdmin(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	IsAdmin, err := helper.GetIsAdminFromCtx(c)
	parentId, err := helper.GetParentIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(c.ShouldBindQuery(param)).Unwrap()
	param.UserLoginIsAdmin = IsAdmin
	// 当前登录用户ID
	if IsAdmin == helper.TypeNumIsAdminAdministrator || (IsAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		param.ParentId = 2
	} else {
		param.ParentId = userId
	}
	data := dao.NewUserDao().GetUserListByIsAdmin(param)
	lists := data.Unwrap().([]*users.UserInfoWithAgent)
	logic.NewUserLogic().FindAllIsAdminUserChildrenListBatch(lists, param.IsAdmin, 0)

	var TotalPage int64
	if param.PageSize > 0 {
		TotalPage = (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize)
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  TotalPage,
		Data:       data.Unwrap(),
	})(OK)
}

//查询签约用户
func GetExtSignUsers(c *gin.Context) {
	//userId, err := helper.GetUserIdFromCtx(c)
	//
	//if err != nil {
	//	Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
	//	return
	//}
	// 请求参数处理
	param := &request.UserList{}

	dingo.ErrorIf(c.ShouldBindQuery(param)).Unwrap()

	//param.ParentId = userId // 当前登录用户ID

	data := dao.NewUserDao().GetExtSignUsersList(param)

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

func HandleBindZfbUserInfo(ctx *gin.Context)  {
	param := &struct {
		UserId      int      `json:"userId"`
		MemberId    int      `json:"memberId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param))
	if param.UserId == 0 {
		Response(ctx)("参数错误", CodeError, false)(OK)
		return
	}
	if param.MemberId > 0 {
		memberInfo := memberdao.NewMemberDao().GetMemberInfoById(param.MemberId).Unwrap().(*membermodel.MembersModel)
		userInfo := dao.NewUserDao().GetUserInfoById(param.UserId).Unwrap().(*users.UserModel)
		zfbUserInfo := dao.NewUserDao().GetUserInfoByZfbOpenid(memberInfo.XcxOpenid).Unwrap().(*users.UserModel)
		if zfbUserInfo.ID > 0 {
			Response(ctx)("此支付宝已绑定过其他帐号", CodeError, false)(OK)
			return
		}
		if userInfo.ID == 0 {
			Response(ctx)("此用户不存在", CodeError, false)(OK)
			return
		}
		if memberInfo.ID == 0 {
			Response(ctx)("会员不存在", CodeError, false)(OK)
			return
		}
		if memberInfo.XcxOpenid == "" {
			Response(ctx)("会员不存在", CodeError, false)(OK)
			return
		}
		if userInfo.ID > 0 && userInfo.ZfbOpenid != "" {
			Response(ctx)("此用户已被绑定", CodeError, false)(OK)
			return
		}
		if userInfo.ZfbOpenid == memberInfo.XcxOpenid {
			Response(ctx)("重复绑定", CodeError, false)(OK)
			return
		}
		data := dao.NewUserDao().UpdateUserZfbBind(param.MemberId, param.UserId, memberInfo.XcxOpenid)
		if data.Err != nil {
			Response(ctx)("绑定失败", CodeError, false)(OK)
			return
		}
		Response(ctx)("绑定成功", CodeSuccess, true)(OK)
	} else {
		data := dao.NewUserDao().UpdateUserZfbUnBind(param.UserId)
		if data.Err != nil {
			Response(ctx)("解绑失败", CodeError, false)(OK)
			return
		}
		Response(ctx)("解绑成功", CodeSuccess, true)(OK)
	}

}

func HandleUnBindZfbUserInfo(ctx *gin.Context)  {
	//param := &struct {
	//	UserId      int      `json:"userId"`
	//	MemberId    int      `json:"memberId"`
	//}{}
	//dingo.ErrorIf(ctx.ShouldBindJSON(param))
	//if param.UserId == 0 {
	//	Response(ctx)("参数错误", CodeError, false)(OK)
	//	return
	//}
	//data := dao.NewUserDao().UpdateUserZfbUnBind(param.UserId)
	//if data.Err != nil {
	//	Response(ctx)("解绑失败", CodeError, false)(OK)
	//	return
	//}
	//Response(ctx)("解绑成功", CodeSuccess, true)(OK)
}
